Convolutional Neural Networks

Project: Write an Algorithm for a Dog Identification App


In this notebook, some template code has already been provided for you, and you will need to implement additional functionality to successfully complete this project. You will not need to modify the included code beyond what is requested. Sections that begin with '(IMPLEMENTATION)' in the header indicate that the following block of code will require additional functionality which you must provide. Instructions will be provided for each section, and the specifics of the implementation are marked in the code block with a 'TODO' statement. Please be sure to read the instructions carefully!

Note: Once you have completed all of the code implementations, you need to finalize your work by exporting the Jupyter Notebook as an HTML document. Before exporting the notebook to html, all of the code cells need to have been run so that reviewers can see the final implementation and output. You can then export the notebook by using the menu above and navigating to File -> Download as -> HTML (.html). Include the finished document along with this notebook as your submission.

In addition to implementing code, there will be questions that you must answer which relate to the project and your implementation. Each section where you will answer a question is preceded by a 'Question X' header. Carefully read each question and provide thorough answers in the following text boxes that begin with 'Answer:'. Your project submission will be evaluated based on your answers to each of the questions and the implementation you provide.

Note: Code and Markdown cells can be executed using the Shift + Enter keyboard shortcut. Markdown cells can be edited by double-clicking the cell to enter edit mode.

The rubric contains optional "Stand Out Suggestions" for enhancing the project beyond the minimum requirements. If you decide to pursue the "Stand Out Suggestions", you should include the code in this Jupyter notebook.


Why We're Here

In this notebook, you will make the first steps towards developing an algorithm that could be used as part of a mobile or web app. At the end of this project, your code will accept any user-supplied image as input. If a dog is detected in the image, it will provide an estimate of the dog's breed. If a human is detected, it will provide an estimate of the dog breed that is most resembling. The image below displays potential sample output of your finished project (... but we expect that each student's algorithm will behave differently!).

Sample Dog Output

In this real-world setting, you will need to piece together a series of models to perform different tasks; for instance, the algorithm that detects humans in an image will be different from the CNN that infers dog breed. There are many points of possible failure, and no perfect algorithm exists. Your imperfect solution will nonetheless create a fun user experience!

The Road Ahead

We break the notebook into separate steps. Feel free to use the links below to navigate the notebook.

  • Step 0: Import Datasets
  • Step 1: Detect Humans
  • Step 2: Detect Dogs
  • Step 3: Create a CNN to Classify Dog Breeds (from Scratch)
  • Step 4: Create a CNN to Classify Dog Breeds (using Transfer Learning)
  • Step 5: Write your Algorithm
  • Step 6: Test Your Algorithm

Personal adjustments

For practical and readability reasons most common imports were moved here on top.

As well, a training function was moved to a subpackage as well as one used to load images. These functions are common code at this stage of the course and keeping them aside helps readability.

In [1]:
# Custom files location on data partition
import os
import numpy as np
import torch
import torch.nn
import torch.nn.functional as F
import torch.optim as optim
from torchvision import transforms
from torchvision import datasets

dog_dir = "/data/picost/ml_samples/dogImages"
human_dir = "/data/picost/ml_samples/lfw"

# Some usefull ressources
import ressources

from my_utils.image_loader import load_image
from my_utils.train_helper import train_model
In [2]:
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
print("Using device : [{}]".format(device))

# check if CUDA is available
use_cuda = torch.cuda.is_available()
Using device : [cpu]

Step 0: Import Datasets

Make sure that you've downloaded the required human and dog datasets:

  • Download the dog dataset. Unzip the folder and place it in this project's home directory, at the location /dogImages.

  • Download the human dataset. Unzip the folder and place it in the home directory, at location /lfw.

Note: If you are using a Windows machine, you are encouraged to use 7zip to extract the folder.

In the code cell below, we save the file paths for both the human (LFW) dataset and dog dataset in the numpy arrays human_files and dog_files.

In [3]:
from glob import glob

# load filenames for human and dog images
human_files = list(glob(os.path.join(human_dir,"*/*")))
dog_files = list(glob(os.path.join(dog_dir, "*/*/*")))

# print number of images in each dataset
print('There are %d total human images.' % len(human_files))
print('There are %d total dog images.' % len(dog_files))
There are 13233 total human images.
There are 8350 total dog images.

Step 1: Detect Humans

In this section, we use OpenCV's implementation of Haar feature-based cascade classifiers to detect human faces in images.

OpenCV provides many pre-trained face detectors, stored as XML files on github. We have downloaded one of these detectors and stored it in the haarcascades directory. In the next code cell, we demonstrate how to use this detector to find human faces in a sample image.

In [4]:
import cv2                
import matplotlib.pyplot as plt                        
%matplotlib inline                               

# extract pre-trained face detector
face_cascade = cv2.CascadeClassifier('haarcascades/haarcascade_frontalface_alt.xml')

# load color (BGR) image
img = cv2.imread(human_files[0])
# convert BGR image to grayscale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# find faces in image
faces = face_cascade.detectMultiScale(gray)

# print number of faces detected in the image
print('Number of faces detected:', len(faces))

# get bounding box for each detected face
for (x,y,w,h) in faces:
    # add bounding box to color image
    cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
    
# convert BGR image to RGB for plotting
cv_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)

# display the image, along with bounding box
plt.imshow(cv_rgb)
plt.show()
Number of faces detected: 1

Before using any of the face detectors, it is standard procedure to convert the images to grayscale. The detectMultiScale function executes the classifier stored in face_cascade and takes the grayscale image as a parameter.

In the above code, faces is a numpy array of detected faces, where each row corresponds to a detected face. Each detected face is a 1D array with four entries that specifies the bounding box of the detected face. The first two entries in the array (extracted in the above code as x and y) specify the horizontal and vertical positions of the top left corner of the bounding box. The last two entries in the array (extracted here as w and h) specify the width and height of the box.

Write a Human Face Detector

We can use this procedure to write a function that returns True if a human face is detected in an image and False otherwise. This function, aptly named face_detector, takes a string-valued file path to an image as input and appears in the code block below.

In [5]:
# returns "True" if face is detected in image stored at img_path
def face_detector(img_path):
    img = cv2.imread(img_path)
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    faces = face_cascade.detectMultiScale(gray)
    return len(faces) > 0

(IMPLEMENTATION) Assess the Human Face Detector

Question 1: Use the code cell below to test the performance of the face_detector function.

  • What percentage of the first 100 images in human_files have a detected human face?
  • What percentage of the first 100 images in dog_files have a detected human face?

Ideally, we would like 100% of human images with a detected face and 0% of dog images with a detected face. You will see that our algorithm falls short of this goal, but still gives acceptable performance. We extract the file paths for the first 100 images from each of the datasets and store them in the numpy arrays human_files_short and dog_files_short.

Answer: (You can print out your results and/or write your percentages in this cell)

In [6]:
#from tqdm import tqdm

human_files_short = human_files[:100]
dog_files_short = dog_files[:100]

#-#-# Do NOT modify the code above this line. #-#-#

## TODO: Test the performance of the face_detector algorithm 
## on the images in human_files_short and dog_files_short.

human_detected = list(map(face_detector, human_files_short))
n_positives = sum(human_detected)
print("The humans were positively detected in [{}]% "
      "cases in the human samples".format(n_positives / len(human_files_short) * 100))
The humans were positively detected in [99.0]% cases in the human samples
In [7]:
dog_human_detected = list(map(face_detector, dog_files_short))
n_false_positives = sum(dog_human_detected)
print("There were [{}]% of false-positive human detection cases in the "
      "dog samples".format(n_false_positives / len(dog_files_short) * 100))
There were [8.0]% of false-positive human detection cases in the dog samples

Let take a look at the false-positive pictures:

In [8]:
import matplotlib.pyplot as plt

for ind, human in enumerate(list(dog_human_detected)):
    if human:
        print(dog_files_short[ind])
        img = cv2.imread(dog_files_short[ind])
        plt.imshow(img)
        plt.show()
/data/picost/ml_samples/dogImages/test/012.Australian_shepherd/Australian_shepherd_00853.jpg
/data/picost/ml_samples/dogImages/test/057.Dalmatian/Dalmatian_04030.jpg
/data/picost/ml_samples/dogImages/test/057.Dalmatian/Dalmatian_04076.jpg
/data/picost/ml_samples/dogImages/test/072.German_shorthaired_pointer/German_shorthaired_pointer_04980.jpg
/data/picost/ml_samples/dogImages/test/002.Afghan_hound/Afghan_hound_00151.jpg
/data/picost/ml_samples/dogImages/test/089.Irish_wolfhound/Irish_wolfhound_06050.jpg
/data/picost/ml_samples/dogImages/test/076.Golden_retriever/Golden_retriever_05248.jpg
/data/picost/ml_samples/dogImages/test/056.Dachshund/Dachshund_03995.jpg

Taking a quick look at the False positive let us see that only one of the eight cases is due of the presence of a human in the dog picture. Therefore, most of them are due to a weakness of the detection algorithm.

We suggest the face detector from OpenCV as a potential way to detect human images in your algorithm, but you are free to explore other approaches, especially approaches that make use of deep learning :). Please use the code cell below to design and test your own face detection algorithm. If you decide to pursue this optional task, report performance on human_files_short and dog_files_short.

(Optional) CNN-based dog-detector

In what follows, a CNN is trained to discriminate dog vs humans in images. The adopted structure for the CNN is the one used in the CIFAR use-case in the CNN class. This architecture gave good results in other tests while remaining quiet simple (therefore not too expensive when training locally)

A dataset had to be created in order to train the classifier. In order to do so, all humans and dogs images were gathered, shuffled and splitted between two groups of samples:

  • 20% of the samples were saved to validate the classifier
  • 80% of the samples were used to train it.

Defining a test set didn't seem necessary here as the main concern is about comparing CNNs vs our basic Haarcascades detectors. Therefore, a small bias toward valdation set is not a big deal and, moreover, as can be seen hereunder, the number of training epochs is very-very-small (only 2 epochs) so there is actually no bias toward the validation set: this bias appears when some models are discarded because they produce higer validation error (but could have been better in testing).

Another point has to be risen : in this particular case, the dataset is imbalanced: there are around 60% more human pictures than dog pictures. Using the dataset as such could lead to a biased detector in favor of humans. As the number of available samples is high enough for this classification task, it seems reasonable to just truncate the human samples, rather that play within the learning to bring back balance to the Force.

In [9]:
Force_imbalance = len(human_files) / len(dog_files)
Force_imbalance
Out[9]:
1.5847904191616766
In [10]:
### (Optional) 
### TODO: Test performance of another face detection algorithm.
### Feel free to use as many code cells as needed.

# 1 create a dataset of shuffled dog and human images with labels
from dogfinder.dog_human_dataset import DogVSHumanDataset
from torch.utils.data.sampler import SubsetRandomSampler

imsize = 224
hd_data = DogVSHumanDataset(dog_files, human_files[:int(len(human_files) / Force_imbalance)], shape=(imsize, imsize))
batch_size = 64

# split data between training and testing
test_ratio = 0.2
indexes = np.arange(0,len(hd_data))
np.random.shuffle(indexes)
split_ix = int(len(indexes) * test_ratio)
train_ix, test_ix = indexes[split_ix:], indexes[:split_ix]
train_sampler = SubsetRandomSampler(train_ix)
test_sampler = SubsetRandomSampler(test_ix)

# Samplers
train_loader = torch.utils.data.DataLoader(hd_data, batch_size=batch_size,
    sampler=train_sampler)
test_loader = torch.utils.data.DataLoader(hd_data, batch_size=batch_size, 
    sampler=test_sampler)
df_loaders = {'train': train_loader, 'valid': test_loader}
In [11]:
# Training
from dogfinder.classifier import Net as DogNet
df_model = DogNet(2, imsize)

train_dir = 'dogfinder_classifier'
save_name = 'mydog_classifier.pt'
dogfinder_crit = torch.nn.CrossEntropyLoss()
dogfinder_optim = optim.Adam(df_model.parameters(), lr=0.001)

The model was trained for only two epochs with a fairly good result on accuracy after such a small number of epochs as can be seen from the output below (pasted from when the model was trained).

train_model(df_model, df_loaders, dogfinder_crit, dogfinder_optim, n_epochs=2, 
            train_dir=train_dir, save_name=save_name)
Starting epoch [1]
Epoch: 1    Training Loss: 0.168805
Epoch: 1    Validation Loss: 0.034192   Accuracy: 0.988922
Saving model...
Create directory: [dogfinder_classifier]
Starting epoch [2]
Epoch: 2    Training Loss: 0.015569
Epoch: 2    Validation Loss: 0.006964   Accuracy: 0.997305
Saving model...

Net(
  (conv1): Conv2d(3, 16, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
  (conv2): Conv2d(16, 32, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
  (conv3): Conv2d(32, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
  (pool): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
  (fc1): Linear(in_features=50176, out_features=500, bias=True)
  (fc2): Linear(in_features=500, out_features=2, bias=True)
  (dropout): Dropout(p=0.25, inplace=False)
)

After beeing trained, the model was tested on the dog_files_short and human_files_short datasets as requested. The test results are given below.

In [12]:
dog_model = DogNet(2, imsize)
dog_model.load_state_dict(torch.load('dogfinder_classifier/mydog_classifier.pt'))
Out[12]:
<All keys matched successfully>
In [13]:
def cnn_predict(img_path):
    '''
    Use trained model to find if a dog or human is present
    
    Args:
        img_path: path to an image
        
    Returns:
        
        int : 0 if a dog is detected, 1 if human.
        
    '''
    ## Load and pre-process an image from the given img_path
    img = load_image(img_path, shape=(224, 224))
    ## Return the *index* of the predicted class for that image
    img = img.to(device)
    cnn_pred = dog_model(img)
    return cnn_pred
In [14]:
### returns "True" if a dog is detected in the image stored at img_path
def dog_detector(img_path):
    """Return True iff a dog is in the provided image
    
    Args: 
    
        img_path (str): path toward a file containing an image to be tested
        
    Returns:
    
        bool : True iff a dog is present in the image
    
    """
    cnn_pred = cnn_predict(img_path)
    top_score, top_index = cnn_pred.topk(1, dim=1)
    label = top_index.item()
    return label == 0
In [15]:
dog_path_example = os.path.join(dog_dir,'train/001.Affenpinscher/Affenpinscher_00001.jpg')
In [16]:
non_dog_path_example = os.path.join(human_dir, 'Zydrunas_Ilgauskas', 'Zydrunas_Ilgauskas_0001.jpg')
In [17]:
dog_detector(dog_path_example)
Out[17]:
True
In [18]:
dog_detector(non_dog_path_example)
Out[18]:
False
In [19]:
### TODO: Test the performance of the dog_detector function
### on the images in human_files_short and dog_files_short.
dogs_detected = list(map(dog_detector, dog_files_short))
n_positives = sum(dogs_detected)
print("Dogs were detected with an accuracy of [{}]%".format(n_positives / len(dog_files_short) * 100))
Dogs were detected with an accuracy of [100.0]%
In [20]:
dogs_detected = list(map(dog_detector, human_files_short))
n_positives = sum(dogs_detected)
print("Dogs were detected in [{}]% of human sample images".format(n_positives / len(dog_files_short) * 100))
Dogs were detected in [1.0]% of human sample images

These are intersting scores!

Let investigate the dog detection among our human samples. Was the network 'hesitating' or pretty categorical for this dog detection among human-labeled pictures?

In [21]:
dog_index = dogs_detected.index(True)
In [22]:
F.softmax(cnn_predict(human_files_short[dog_index]), dim=1)
Out[22]:
tensor([[0.7408, 0.2592]], grad_fn=<SoftmaxBackward>)

The network was really wrong in this case... Let take a look at the picture that mislead it.

In [23]:
ind = dogs_detected.index(1) # True == 1 in Python
print("Dog detected in :", human_files_short[ind])
img = cv2.imread(human_files_short[ind])
plt.imshow(img)
plt.show()
Dog detected in : /data/picost/ml_samples/lfw/Brad_Wilk/Brad_Wilk_0001.jpg

This is actually a real mistake from the network as any human sees another human beeing there.

Despite the misclassification displayed here-over, the network performs pretty well and outperforms the haarcascades in detecting dogs and humans after only two epochs of training. More accurately, using our CNN has a better precision when it comes to detecting dogs: it gives less false-positive dog detections (1 for the CNN vs 8 for haarcascades).

In [24]:
# number of dog images from dog_files_short that are present in the training set
len(train_ix[train_ix < 100])
Out[24]:
71
In [25]:
# number of human images from human_files_short that are present in the training set
len([ix for ix in train_ix if len(dog_files) + 100 > ix and ix > len(dog_files)])
Out[25]:
76

Finally, as illustrated in the previous cells, it can be noticed that some (most actually) of the images in human_files_short and dog_files_short were used in the training set. However, the validation accuracy beeing over 99.7% for the CNN classifier, the obtained result with human_files_short and dog_files_short seems nonetheless trustworthy.


Step 2: Detect Dogs

In this section, we use a pre-trained model to detect dogs in images.

Obtain Pre-trained VGG-16 Model

The code cell below downloads the VGG-16 model, along with weights that have been trained on ImageNet, a very large, very popular dataset used for image classification and other vision tasks. ImageNet contains over 10 million URLs, each linking to an image containing an object from one of 1000 categories.

In [26]:
import torchvision.models as models

# define VGG16 model
VGG16 = models.vgg16(pretrained=True)

# move model to GPU if CUDA is available
VGG16 = VGG16.to(device)

Given an image, this pre-trained VGG-16 model returns a prediction (derived from the 1000 possible categories in ImageNet) for the object that is contained in the image.

In [27]:
VGG16
Out[27]:
VGG(
  (features): Sequential(
    (0): Conv2d(3, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (1): ReLU(inplace=True)
    (2): Conv2d(64, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (3): ReLU(inplace=True)
    (4): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
    (5): Conv2d(64, 128, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (6): ReLU(inplace=True)
    (7): Conv2d(128, 128, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (8): ReLU(inplace=True)
    (9): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
    (10): Conv2d(128, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (11): ReLU(inplace=True)
    (12): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (13): ReLU(inplace=True)
    (14): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (15): ReLU(inplace=True)
    (16): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
    (17): Conv2d(256, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (18): ReLU(inplace=True)
    (19): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (20): ReLU(inplace=True)
    (21): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (22): ReLU(inplace=True)
    (23): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
    (24): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (25): ReLU(inplace=True)
    (26): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (27): ReLU(inplace=True)
    (28): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (29): ReLU(inplace=True)
    (30): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
  )
  (avgpool): AdaptiveAvgPool2d(output_size=(7, 7))
  (classifier): Sequential(
    (0): Linear(in_features=25088, out_features=4096, bias=True)
    (1): ReLU(inplace=True)
    (2): Dropout(p=0.5, inplace=False)
    (3): Linear(in_features=4096, out_features=4096, bias=True)
    (4): ReLU(inplace=True)
    (5): Dropout(p=0.5, inplace=False)
    (6): Linear(in_features=4096, out_features=1000, bias=True)
  )
)

(IMPLEMENTATION) Making Predictions with a Pre-trained Model

In the next code cell, you will write a function that accepts a path to an image (such as 'dogImages/train/001.Affenpinscher/Affenpinscher_00001.jpg') as input and returns the index corresponding to the ImageNet class that is predicted by the pre-trained VGG-16 model. The output should always be an integer between 0 and 999, inclusive.

Before writing the function, make sure that you take the time to learn how to appropriately pre-process tensors for pre-trained models in the PyTorch documentation.

The following cell contains a function to load an image as defined from the style-transfer notebook in the course.

In [28]:
def VGG16_predict(img_path):
    '''
    Use pre-trained VGG-16 model to obtain index corresponding to 
    predicted ImageNet class for image at specified path
    
    Args:
        img_path: path to an image
        
    Returns:
        Index corresponding to VGG-16 model's prediction
    '''
    ## TODO: Complete the function.
    ## Load and pre-process an image from the given img_path
    vgg_in = load_image(img_path, shape=(224, 224))
    ## Return the *index* of the predicted class for that image
    vgg_in = vgg_in.to(device)
    vgg_pred = VGG16(vgg_in)
    top_score, top_index = vgg_pred.topk(1, dim=1)
    return top_index # predicted class index

Test the function on a the dog file uses as example in the text:

In [29]:
dog_path_example = os.path.join(dog_dir,'train/001.Affenpinscher/Affenpinscher_00001.jpg')
class_index = VGG16_predict(dog_path_example).item()
print(class_index)
252

The result is correct for this example.

In [30]:
non_dog_path_example = os.path.join(human_dir, 'Zydrunas_Ilgauskas', 'Zydrunas_Ilgauskas_0001.jpg')
class_index = VGG16_predict(non_dog_path_example).item()
ressources.vgg_class_labels[class_index]
Out[30]:
'horizontal bar, high bar'

Ok since no human in label classes: this is not a dog!

(IMPLEMENTATION) Write a Dog Detector

While looking at the dictionary, you will notice that the categories corresponding to dogs appear in an uninterrupted sequence and correspond to dictionary keys 151-268, inclusive, to include all categories from 'Chihuahua' to 'Mexican hairless'. Thus, in order to check to see if an image is predicted to contain a dog by the pre-trained VGG-16 model, we need only check if the pre-trained model predicts an index between 151 and 268 (inclusive).

Use these ideas to complete the dog_detector function below, which returns True if a dog is detected in an image (and False if not).

In [31]:
### returns "True" if a dog is detected in the image stored at img_path
def dog_detector(img_path):
    """Return True iff a dog is in the provided image
    
    Args: 
    
        img_path (str): path toward a file containing an image to be tested
        
    Returns:
    
        bool : True iff a dog is present in the image
    
    """
    label = VGG16_predict(img_path).item()
    return (label > 150 and label < 269)
In [32]:
### returns "True" if a dog is detected in the image stored at img_path
def dog_detector(img_path):
    """Return True iff a dog is in the provided image
    
    Args: 
    
        img_path (str): path toward a file containing an image to be tested
        
    Returns:
    
        bool : True iff a dog is present in the image
    
    """
    label = VGG16_predict(img_path).item()
    return (label > 150 and label < 269)
In [33]:
dog_detector(dog_path_example)
Out[33]:
True
In [34]:
dog_detector(non_dog_path_example)
Out[34]:
False

(IMPLEMENTATION) Assess the Dog Detector

Question 2: Use the code cell below to test the performance of your dog_detector function.

  • What percentage of the images in human_files_short have a detected dog?
  • What percentage of the images in dog_files_short have a detected dog?

Answer:

In [35]:
### TODO: Test the performance of the dog_detector function
### on the images in human_files_short and dog_files_short.
dogs_detected = list(map(dog_detector, dog_files_short))
n_positives = sum(dogs_detected)
print("Dogs were detected with an accuracy of [{}]%".format(n_positives / len(dog_files_short) * 100))
Dogs were detected with an accuracy of [100.0]%
In [36]:
dogs_detected = list(map(dog_detector, human_files_short))
n_positives = sum(dogs_detected)
print("Dogs were detected in [{}]% of human sample images".format(n_positives / len(dog_files_short) * 100))
Dogs were detected in [1.0]% of human sample images
In [37]:
ind = dogs_detected.index(1) # True == 1 in Python
print("Dog detected in :", human_files_short[ind])
img = cv2.imread(human_files_short[ind])
plt.imshow(img)
plt.show()
Dog detected in : /data/picost/ml_samples/lfw/Albert_Brooks/Albert_Brooks_0001.jpg

The VGG16 network is much more precise that the haarcascade when it comes to dog detection. Still, one can notice that the network performance is similar to which of our custom network on this example.

If I were to dig a little more into the results of this prediction, it would be interesting to check wether all the dog breeds in dog_files_short belong to the VGG16 dictionnary or not. It may not be the case but, if so, one could see that this networks still classifies an unknow dog breed as a dog.

We suggest VGG-16 as a potential network to detect dog images in your algorithm, but you are free to explore other pre-trained networks (such as Inception-v3, ResNet-50, etc). Please use the code cell below to test other pre-trained PyTorch models. If you decide to pursue this optional task, report performance on human_files_short and dog_files_short.

In [38]:
### (Optional) 
### TODO: Report the performance of another pre-trained network.
### Feel free to use as many code cells as needed.

Step 3: Create a CNN to Classify Dog Breeds (from Scratch)

Now that we have functions for detecting humans and dogs in images, we need a way to predict breed from images. In this step, you will create a CNN that classifies dog breeds. You must create your CNN from scratch (so, you can't use transfer learning yet!), and you must attain a test accuracy of at least 10%. In Step 4 of this notebook, you will have the opportunity to use transfer learning to create a CNN that attains greatly improved accuracy.

We mention that the task of assigning breed to dogs from images is considered exceptionally challenging. To see why, consider that even a human would have trouble distinguishing between a Brittany and a Welsh Springer Spaniel.

Brittany Welsh Springer Spaniel

It is not difficult to find other dog breed pairs with minimal inter-class variation (for instance, Curly-Coated Retrievers and American Water Spaniels).

Curly-Coated Retriever American Water Spaniel

Likewise, recall that labradors come in yellow, chocolate, and black. Your vision-based algorithm will have to conquer this high intra-class variation to determine how to classify all of these different shades as the same breed.

Yellow Labrador Chocolate Labrador Black Labrador

We also mention that random chance presents an exceptionally low bar: setting aside the fact that the classes are slightly imabalanced, a random guess will provide a correct answer roughly 1 in 133 times, which corresponds to an accuracy of less than 1%.

Remember that the practice is far ahead of the theory in deep learning. Experiment with many different architectures, and trust your intuition. And, of course, have fun!

(IMPLEMENTATION) Specify Data Loaders for the Dog Dataset

Use the code cell below to write three separate data loaders for the training, validation, and test datasets of dog images (located at dogImages/train, dogImages/valid, and dogImages/test, respectively). You may find this documentation on custom datasets to be a useful resource. If you are interested in augmenting your training and/or validation data, check out the wide variety of transforms!

In [39]:
batch_size = 16
imsize = 80

transform = transforms.Compose([
    transforms.Resize(int(imsize * 1.2) ),
    transforms.RandomHorizontalFlip(), 
    transforms.RandomRotation(30),
    transforms.RandomCrop(imsize),
    transforms.ToTensor(),
    transforms.Normalize((0.485, 0.456, 0.406), 
                         (0.229, 0.224, 0.225)),
    ])

test_transform = transforms.Compose([
    transforms.Resize(int(imsize * 1.2) ),
    transforms.CenterCrop(imsize),
    transforms.ToTensor(),
    transforms.Normalize((0.485, 0.456, 0.406), 
                         (0.229, 0.224, 0.225)),
    ])

# Training Dataset
train_dir = os.path.join(dog_dir, 'train')
train_set = datasets.ImageFolder(train_dir, transform=transform)
train_loader = torch.utils.data.DataLoader(train_set, batch_size=batch_size, 
                                           shuffle=True)
# validation Dataset
valid_dir = os.path.join(dog_dir, 'valid')
valid_set = datasets.ImageFolder(valid_dir, transform=test_transform)
valid_loader = torch.utils.data.DataLoader(valid_set, batch_size=batch_size, 
                                           shuffle=True)
# Test Dataset
test_dir = os.path.join(dog_dir, 'test')
test_set = datasets.ImageFolder(test_dir, transform=test_transform)
test_loader = torch.utils.data.DataLoader(test_set, batch_size=batch_size, 
                                          shuffle=True)

loaders_scratch = {'train': train_loader,
                   'valid': valid_loader,
                   'test': test_loader}
In [ ]:
n_class = 0
for data, target in train_loader:
    n_class = max(n_class, target.max())
In [40]:
n_class = 133
In [41]:
n_train = len(train_set)
n_valid = len(valid_set)
n_test = len(test_set)
print("There are {} images for training, {} for validation and {} for testing".format(n_train, n_valid, n_test))
There are 6679 images for training, 835 for validation and 836 for testing
In [42]:
import helpers
images, labels = next(iter(train_loader))
helpers.imshow(images[0], normalize=True)
Out[42]:
<matplotlib.axes._subplots.AxesSubplot at 0x7f8db542dcd0>

Question 3: Describe your chosen procedure for preprocessing the data.

  • How does your code resize the images (by cropping, stretching, etc)? What size did you pick for the input tensor, and why?
  • Did you decide to augment the dataset? If so, how (through translations, flips, rotations, etc)? If not, why not?

Answer:

I choose to let torchvision resize the images for me using the torchvision.Resize transformation which streches the pictures using a bilinear transformation according to the doc. The final image size was chosen directly to fit the input shape of the network to be trained. In the present case, it was chosen to feed the network with 80x80 pictures. This was a compromise between:

  • conserving enough of the original image information to enable the network to discriminate between dogs breed
  • lowering the number of features and parameters in the network to minimize the training cost

Within the chosen three-convolutional-layer architecture, the number of description feature in each channel is divided by 4 at each of the convolution step while the number of channel is increased by a factor 2 (except in the first one from 3 to 16). After the convolution, the remaining number of features is with an 80x80x3 input image 6400 which gives a reasonable number of parameters ($\approx 3.10^7$) to be fitted (with dropout) in the linear layers, which contain by far the highest number of hyper-parameters.

As the targeted accuracy for this part of the assignment is reasonably small (10%), the chosen resolution seemed a good compromise. This choice is therfore quiet arbitrary, the only constraint comming form the network beeing that the number of pixels in each dimension must be a multiple of 8 as.

Eventually, all the pictures were resized to 120% of the desired final size, which let enough room to apply the augmentation procedure which consisted in :

  • rotating randomly the picture with a 30° amplitude
  • flipping randomly the picture horizontally
  • randomly cropping the picture at the desired size.

Vertical flip was not applied as it seamed a reasonable assumption in the present case that no dog pictures would be upside-down. As convolutional neural networks are not rotation-invariant, accounting for this case would maybe have required a more complex network (although I admit that I did not perform the comparison).

Another common practice is to use TenCrops but as our dataset looks to contain subjects that occupy most of the picture, random crops seemed relevant as well.

(IMPLEMENTATION) Model Architecture

Create a CNN to classify dog breed. Use the template in the code cell below.

# CNN architecture for dog classifier:

class Net(nn.Module):
    def __init__(self, n_class, imsize):
        super(Net, self).__init__()
        assert (imsize % 8 == 0), "Imsize must be a divisible by 8"
        # convolutional layer (sees 80x80x3 image tensor)
        self.conv1 = nn.Conv2d(3, 16, 3, padding=1)
        # convolutional layer (sees 40x40x16 tensor)
        self.conv2 = nn.Conv2d(16, 32, 3, padding=1)
        # convolutional layer (sees 20x20x32 tensor)
        self.conv3 = nn.Conv2d(32, 64, 3, padding=1)
        # final classifier sees 10x10x64 features
        # max pooling layer
        self.pool = nn.MaxPool2d(2, 2)
        self.n_feat = int(imsize / 8)
        # linear layer (64 * 10 * 10 -> 500)
        self.fc1 = nn.Linear(64 * self.n_feat * self.n_feat, 500)
        # linear layer (500 -> 10)
        self.fc2 = nn.Linear(500, n_class)
        # dropout layer (p=0.25)
        self.dropout = nn.Dropout(0.25)

    def forward(self, x):
        # add sequence of convolutional and max pooling layers
        x = self.pool(F.relu(self.conv1(x)))
        x = self.pool(F.relu(self.conv2(x)))
        x = self.pool(F.relu(self.conv3(x)))
        # flatten image input
        x = x.view(-1, 64 * self.n_feat * self.n_feat)
        # add dropout layer
        x = self.dropout(x)
        # add 1st hidden layer, with relu activation function
        x = F.relu(self.fc1(x))
        # add dropout layer
        x = self.dropout(x)
        # add 2nd hidden layer, with relu activation function
        x = self.fc2(x)
        return x
In [43]:
from cifar_model.dog_classifier import Net

# instantiate the CNN
model_scratch = Net(n_class, imsize)

# move tensors to GPU if CUDA is available
if use_cuda:
    model_scratch.cuda()

Question 4: Outline the steps you took to get to your final CNN architecture and your reasoning at each step.

Answer:

I tried various architectures with more or less (one to three) convolutional layers. However, I faced the problem of vanishing gradient, my network beeing quickly stuck at a given error rate with no movement while training.

Therefore, I tried simplifying the problem and making it less expensive as (shallower network, lower image resolution) to be quicker in trial and error as:

  • I train locally
  • There is few data (<7000 images) vs number of classes to be discriminated

Finally, I adopted the architecture from the CIFAR exercises in the CNNs notebook as it fitted weel my needs : it is simple and not to expensive to train, and it performed quiet well on this task.

In order to reduce the number of parameters to be fitted, I limitted the input resolution to 80 x 80 which seemed enough as the target accuracy in this case was quiet limitted. I could also have tried to achieve a similar result by using wider kernels in the pooling layers (as only number of parameters in the linear layers is affected by the size of the input samples, not the convolutional ones), but I did not take the time to try it.

Also, I restarted the optimization only once (accidentaly actually, and got a lower accuracy...). Using a proper multiple restart - first compute a few iterations from various starting points and investigate further the best ones - could probably have returned a better result.

(IMPLEMENTATION) Specify Loss Function and Optimizer

Use the next code cell to specify a loss function and optimizer. Save the chosen loss function as criterion_scratch, and the optimizer as optimizer_scratch below.

In [44]:
### TODO: select loss function
criterion_scratch = torch.nn.CrossEntropyLoss()

### TODO: select optimizer
optimizer_scratch = optim.Adam(model_scratch.parameters(), lr=0.001)

(IMPLEMENTATION) Train and Validate the Model

Train and validate your model in the code cell below. Save the final model parameters at filepath 'model_scratch.pt'.

In [45]:
model_scratch.load_state_dict(torch.load('cifar_model/model.pt'))
Out[45]:
<All keys matched successfully>
import my_utils.train_helper
from my_utils.train_helper import train_model

train_model(model_scratch, loaders_scratch, criterion_scratch, optimizer_scratch, n_epochs=100)
In [46]:
import pandas as pd
scratch_hist = pd.read_csv('cifar_model/train_hist.csv', index_col='epoch')
scratch_hist
Out[46]:
train_loss valid_loss accuracy
epoch
1 4.782002 4.548273 0.033533
2 4.464426 4.300806 0.049102
3 4.295806 4.134139 0.071856
4 4.154748 3.987249 0.088623
5 4.047045 3.921264 0.098204
... ... ... ...
96 2.134342 3.825779 0.221557
97 2.165592 4.017651 0.219162
98 2.138431 3.729464 0.245509
99 2.140954 3.839023 0.231138
100 2.107098 3.815768 0.237126

100 rows × 3 columns

In [47]:
scratch_hist.plot()
Out[47]:
<matplotlib.axes._subplots.AxesSubplot at 0x7f8db5871310>

(IMPLEMENTATION) Test the Model

Try out your model on the test dataset of dog images. Use the code cell below to calculate and print the test loss and accuracy. Ensure that your test accuracy is greater than 10%.

In [48]:
model_scratch.load_state_dict(torch.load('cifar_model/model.pt'))
model_scratch.eval()
Out[48]:
Net(
  (conv1): Conv2d(3, 16, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
  (conv2): Conv2d(16, 32, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
  (conv3): Conv2d(32, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
  (pool): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
  (fc1): Linear(in_features=6400, out_features=500, bias=True)
  (fc2): Linear(in_features=500, out_features=133, bias=True)
  (dropout): Dropout(p=0.25, inplace=False)
)
In [49]:
def test(loaders, model, criterion, use_cuda):

    # monitor test loss and accuracy
    test_loss = 0.
    correct = 0.
    total = 0.

    model.eval()
    for batch_idx, (data, target) in enumerate(loaders['test']):
        # move to GPU
        if use_cuda:
            data, target = data.cuda(), target.cuda()
        # forward pass: compute predicted outputs by passing inputs to the model
        output = model(data)
        # calculate the loss
        loss = criterion(output, target)
        # update average test loss 
        test_loss = test_loss + ((1 / (batch_idx + 1)) * (loss.data - test_loss))
        # convert output probabilities to predicted class
        pred = output.data.max(1, keepdim=True)[1]
        # compare predictions to true label
        correct += np.sum(np.squeeze(pred.eq(target.data.view_as(pred))).cpu().numpy())
        total += data.size(0)
            
    print('Test Loss: {:.6f}\n'.format(test_loss))

    print('\nTest Accuracy: %2d%% (%2d/%2d)' % (
        100. * correct / total, correct, total))
In [50]:
# call test function    
test(loaders_scratch, model_scratch, criterion_scratch, use_cuda)
Test Loss: 3.765067


Test Accuracy: 23% (194/836)

Looking at the validation loss curve, it is pretty obvious that the accuracy is the best one that can be achieved for this network and this training procedure (initialization, learning rate, keept constant here). Training for 100 epochs was a little overkill as the best validation loss stopped decreasing after less than 20 iterations.

Still, this accuracy is decent for such a simple and cheap network and a complex task! Another starting point for the optimisation (accidentaly discarded) gave a similar but slightly better value of 27%, still far from the more expensive but more accurate classifier we are about to build in the next section.


Step 4: Create a CNN to Classify Dog Breeds (using Transfer Learning)

You will now use transfer learning to create a CNN that can identify dog breed from images. Your CNN must attain at least 60% accuracy on the test set.

(IMPLEMENTATION) Specify Data Loaders for the Dog Dataset

Use the code cell below to write three separate data loaders for the training, validation, and test datasets of dog images (located at dogImages/train, dogImages/valid, and dogImages/test, respectively).

If you like, you are welcome to use the same data loaders from the previous step, when you created a CNN from scratch.

In [51]:
batch_size = 64
imsize = 224

transform = transforms.Compose([
    transforms.Resize(int(imsize * 1.2) ),
    transforms.RandomHorizontalFlip(), 
    transforms.RandomCrop(imsize),
    transforms.ToTensor(),
    transforms.Normalize((0.485, 0.456, 0.406), 
                         (0.229, 0.224, 0.225)),
    ])

test_transform = transforms.Compose([
    transforms.Resize(int(imsize * 1.2) ),
    transforms.CenterCrop(imsize),
    transforms.ToTensor(),
    transforms.Normalize((0.485, 0.456, 0.406), 
                         (0.229, 0.224, 0.225)),
    ])

# Training Dataset
train_dir = os.path.join(dog_dir, 'train')
train_set = datasets.ImageFolder(train_dir, transform=transform)
train_loader = torch.utils.data.DataLoader(train_set, batch_size=batch_size, 
                                           shuffle=True)
# validation Dataset
valid_dir = os.path.join(dog_dir, 'valid')
valid_set = datasets.ImageFolder(valid_dir, transform=test_transform)
valid_loader = torch.utils.data.DataLoader(valid_set, batch_size=batch_size, 
                                           shuffle=True)
# Test Dataset
test_dir = os.path.join(dog_dir, 'test')
test_set = datasets.ImageFolder(test_dir, transform=test_transform)
test_loader = torch.utils.data.DataLoader(test_set, batch_size=batch_size, 
                                          shuffle=True)

loaders_transfer = {'train': train_loader,
                    'valid': valid_loader,
                    'test': test_loader}

(IMPLEMENTATION) Model Architecture

Use transfer learning to create a CNN to classify dog breed. Use the code cell below, and save your initialized model as the variable model_transfer.

It can be noticed that some of the output classes of the original ImageNet networks are dog breees that are present in our target class. Therefore, I first attempted to find which were the common classes between our classification tasks.

Classes that we are trying to classify:

In [52]:
class_names = [item[4:].replace("_", " ").lower().strip() for item in train_set.classes]

Classes the networ can already classify

In [53]:
existing_classes = [ressources.vgg_class_labels[i].lower() for i in range(151, 269)]

Match the lists:

In [54]:
matches_ind = {}
matches_name = {}
reverse_matches_ind = {}
lonely_existing = []
lonely_search = []
for ind, dog_name in enumerate(existing_classes):
    variants = [dg.strip() for dg in dog_name.split(',')]
    for variant in variants:
        try:
            found = class_names.index(variant)
            matches_ind[ind] = found
            reverse_matches_ind[found] = ind
            matches_name[ind] = variant
            break
        except:
            continue
    else:
        lonely_existing.append((ind,dog_name))
lonely_search = [element for element in class_names if element not in matches_name.values()]
print('Found [{}/{}] matches'.format(len(matches_ind), len(existing_classes)))
print('index in existing classes : name')
#matches_name
#reverse_matches_ind
Found [72/118] matches
index in existing classes : name

reverse_matches_ind dict contains indexes of classes in the current classification task as keys. The values are the indexes of the matching class in those originally classified by the network.

In [55]:
import torchvision.models as models
import torch.nn as nn

## Specify model architecture 
train_dir = 'vgg19_transfer'
save_name = 'model_transfer.pt'
model_transfer = models.vgg19(pretrained=True)

# Freeze training for all "features" layers
for param in model_transfer.features.parameters():
    param.requires_grad = False
    
if use_cuda:
    model_transfer = model_transfer.cuda()
In [56]:
model_transfer
Out[56]:
VGG(
  (features): Sequential(
    (0): Conv2d(3, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (1): ReLU(inplace=True)
    (2): Conv2d(64, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (3): ReLU(inplace=True)
    (4): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
    (5): Conv2d(64, 128, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (6): ReLU(inplace=True)
    (7): Conv2d(128, 128, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (8): ReLU(inplace=True)
    (9): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
    (10): Conv2d(128, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (11): ReLU(inplace=True)
    (12): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (13): ReLU(inplace=True)
    (14): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (15): ReLU(inplace=True)
    (16): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (17): ReLU(inplace=True)
    (18): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
    (19): Conv2d(256, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (20): ReLU(inplace=True)
    (21): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (22): ReLU(inplace=True)
    (23): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (24): ReLU(inplace=True)
    (25): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (26): ReLU(inplace=True)
    (27): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
    (28): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (29): ReLU(inplace=True)
    (30): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (31): ReLU(inplace=True)
    (32): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (33): ReLU(inplace=True)
    (34): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (35): ReLU(inplace=True)
    (36): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
  )
  (avgpool): AdaptiveAvgPool2d(output_size=(7, 7))
  (classifier): Sequential(
    (0): Linear(in_features=25088, out_features=4096, bias=True)
    (1): ReLU(inplace=True)
    (2): Dropout(p=0.5, inplace=False)
    (3): Linear(in_features=4096, out_features=4096, bias=True)
    (4): ReLU(inplace=True)
    (5): Dropout(p=0.5, inplace=False)
    (6): Linear(in_features=4096, out_features=1000, bias=True)
  )
)
In [57]:
for param in model_transfer.classifier.parameters():
    param.requires_grad = True
In [58]:
model_transfer.classifier[6].out_features = n_class

vgg19_last_layer = model_transfer.classifier[6]
# reset last layers weights for optim
model_transfer.classifier[6] = nn.Linear(4096, n_class)
for elt in [6]:
    n_in_layer = model_transfer.classifier[elt].in_features
    model_transfer.classifier[elt].weight.data.normal_(0, 1/np.sqrt(n_in_layer))
# reuse classes from vgg16
for class_index, match_index in reverse_matches_ind.items():
    model_transfer.classifier[6].weight.data[class_index, :] = vgg19_last_layer.weight.data[match_index, :]
    model_transfer.classifier[6].bias.data[class_index] = vgg19_last_layer.bias.data[match_index]

Question 5: Outline the steps you took to get to your final CNN architecture and your reasoning at each step. Describe why you think the architecture is suitable for the current problem.

Answer:

Initially, I had no clue about how to chose a starting point among the models available in torchvision. I took a look at the available models, their accuracies and structures as well as the main idea that lead to tadopt them. Finally, I decided to give a try with a model:

  1. which last layers were dense linear ones
  2. with a small numbrer of parameters to be trained.

Point n.2 looked to be good in the sense that optimization complexity seemed reduced, with the risk of uncertain generalization ability.

I performed a first test with MobileNet architecture which was not conclusive. After trying a few other architectures, I realized that my training code was bugged in a very silly way: I did not train the parameters from the right model...

I finally used VGG19 as I had some ideas in mind for which knowing the layer to be fitted in order to keep the sementical information from an image could be usefull (see https://www.cv-foundation.org/openaccess/content_cvpr_2016/papers/Gatys_Image_Style_Transfer_CVPR_2016_paper.pdf and the style-transfer assignment), as discussed at the end of this assignment. I did not re-try other architectures or numerous optimization starting point as training this network remains a costly task especially when training locally.

In order to provide a relevant initial set of weights for the classifier, I used the fact that the original VGG19 network was already trained to classify some of the dog breeds in our dataset. After identifying which of the original output classes from VGG19 were also present in our dataset, the network classifier was initialized as follows:

  • the weights and bias for the already existing classes were initializd with their values from original VGG19
  • the weights and bias for the other classes were initialiazd randomly, with a normal distribution for the weights as tought in the course material.

Using this initialization procedure, a 49% validation accuracy is obtained after the first training epoch and around 70% after 10 epoch. In order to check if this procedure was relevant, another model, initialized only from normal distributrion this time, was trained for 10 epoch. This model had a 65% accuracy after the first training epoch and a 70% accuracy after 10 epochs. This leads to the two following conclusions:

  • 1) The initialization procedure which reused "trained" weights for a part of the network was therefore a counter-efficient idea in this case.
  • 2) The transfer learning approach is very effective for this classification task!

Point 2) is not a surprise as VGG19 network was trained to classify images thae contained 118 dog breeds, 78 of which belong to our target classes. The present case is therfore the one of training on similar tasks with a small dataset which is the one for which transfer learning is the best suited.

Trying to understand properly why this procedure is counter-productive would require a thorough investigation during the optimization process which is not the point of this exercise. However, my assumption regarding point 1) would be that the very different maturity of the weights for different classes can be at the origin of this problem in the following way:

  • There are 3 fully connected layers in the calssifier.
  • The first two layers have the original VGG19 weights.
  • In the last layer, the weights for existing classes are reused (after matching the indices) and those of new classes are randomly initialized.

At the beginning of the training:

  • When a new sample comes for a "new" class label, ALL the classifier weigts are changed, including those of the first two layers. This can degrade the accuracy for the previously existing class as the weights were already fitted.
  • When a new sample comes for an existing class label, the weights in the first two layers are moved "back" toward their initial values. This would introduce a kind of competition between the new and pre-existing classes in the choice of the weights, explaining why the accuracy is degraded at the beginning io the training.

This phenomenon could be assimilated to the one described in this paper about transfer learning. The authors notice that re-training a network while keeping the weights from the first layers can actually degrade accuracy when truncating at the network "in the middle", where the weights were "fragily co-adapted"

Finally, in both case, the network produce a decent accuracy, well above 60% in both cases after a few training steps.

(IMPLEMENTATION) Specify Loss Function and Optimizer

Use the next code cell to specify a loss function and optimizer. Save the chosen loss function as criterion_transfer, and the optimizer as optimizer_transfer below.

In [59]:
criterion_transfer = torch.nn.CrossEntropyLoss()
optimizer_transfer = optim.Adam(model_transfer.parameters(), lr=0.001)

(IMPLEMENTATION) Train and Validate the Model

Train and validate your model in the code cell below. Save the final model parameters at filepath 'model_transfer.pt'.

Find the training code below:

try:
    model_transfer.load_state_dict(torch.load(os.path.join(train_dir, save_name)))
except:
    pass
import my_utils.train_helper
from my_utils.train_helper import train_model
model_transfer = train_model(model_transfer, loaders_transfer, criterion_transfer, 
                             optimizer_transfer, train_dir=train_dir, save_name=save_name, 
                             n_epochs=20)


# load the model that got the best validation accuracy (uncomment the line below)
model_transfer.load_state_dict(torch.load(os.path.join(train_dir, save_name)))

The model was trained using the code here-over. The trainging history can be seen as a table and a graph below.

In [60]:
import pandas as pd
vgg19_hist = pd.read_csv('vgg19_transfer/train_hist.csv', index_col='epoch')
vgg19_hist
Out[60]:
train_loss valid_loss accuracy
epoch
1 4.094813 1.800114 0.493413
2 2.778474 1.198870 0.631138
3 2.544764 1.229837 0.614371
4 2.361078 1.141281 0.668263
5 2.322141 1.072439 0.655090
6 2.248702 1.065870 0.689820
7 2.205840 1.039583 0.682635
8 2.200557 0.952914 0.714970
9 2.248913 1.010297 0.691018
10 2.153910 0.963215 0.700599
11 2.106589 0.932724 0.714970
12 2.028065 0.934342 0.701796
13 2.070484 0.915994 0.722156
14 2.051476 0.930876 0.723353
15 2.110711 0.962601 0.704192
16 2.022218 0.943146 0.691018
17 2.074424 0.913977 0.718563
18 1.972119 0.899126 0.716168
19 2.043392 0.909374 0.712575
20 2.028811 0.843454 0.713772
21 1.906430 0.811654 0.756886
22 2.016137 0.842689 0.740120
In [61]:
vgg19_hist.plot()
Out[61]:
<matplotlib.axes._subplots.AxesSubplot at 0x7f8db140c250>
In [62]:
# load the model that got the best validation accuracy (uncomment the line below)
model_transfer.load_state_dict(torch.load(os.path.join(train_dir, save_name)))
model_transfer.eval()
Out[62]:
VGG(
  (features): Sequential(
    (0): Conv2d(3, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (1): ReLU(inplace=True)
    (2): Conv2d(64, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (3): ReLU(inplace=True)
    (4): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
    (5): Conv2d(64, 128, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (6): ReLU(inplace=True)
    (7): Conv2d(128, 128, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (8): ReLU(inplace=True)
    (9): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
    (10): Conv2d(128, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (11): ReLU(inplace=True)
    (12): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (13): ReLU(inplace=True)
    (14): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (15): ReLU(inplace=True)
    (16): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (17): ReLU(inplace=True)
    (18): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
    (19): Conv2d(256, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (20): ReLU(inplace=True)
    (21): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (22): ReLU(inplace=True)
    (23): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (24): ReLU(inplace=True)
    (25): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (26): ReLU(inplace=True)
    (27): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
    (28): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (29): ReLU(inplace=True)
    (30): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (31): ReLU(inplace=True)
    (32): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (33): ReLU(inplace=True)
    (34): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (35): ReLU(inplace=True)
    (36): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
  )
  (avgpool): AdaptiveAvgPool2d(output_size=(7, 7))
  (classifier): Sequential(
    (0): Linear(in_features=25088, out_features=4096, bias=True)
    (1): ReLU(inplace=True)
    (2): Dropout(p=0.5, inplace=False)
    (3): Linear(in_features=4096, out_features=4096, bias=True)
    (4): ReLU(inplace=True)
    (5): Dropout(p=0.5, inplace=False)
    (6): Linear(in_features=4096, out_features=133, bias=True)
  )
)

(IMPLEMENTATION) Test the Model

Try out your model on the test dataset of dog images. Use the code cell below to calculate and print the test loss and accuracy. Ensure that your test accuracy is greater than 60%.

In [63]:
test(loaders_transfer, model_transfer, criterion_transfer, use_cuda)
Test Loss: 1.011628


Test Accuracy: 71% (601/836)

(IMPLEMENTATION) Predict Dog Breed with the Model

Write a function that takes an image path as input and returns the dog breed (Affenpinscher, Afghan hound, etc) that is predicted by your model.

In [64]:
### TODO: Write a function that takes a path to an image as input
### and returns the dog breed that is predicted by the model.

# list of class names by index, i.e. a name can be accessed like class_names[0]
class_names = [item[4:].replace("_", " ") for item in train_set.classes]

def predict_breed_transfer(img_path):
    """Return the most likely detected dog breed in the image.
    
    Args:
    
        img_path (str): path toward the image where the dog is looked for
        
    Returns:
    
        str: name of the most likely detected dog breed in the image
    
    """
    image = load_image(img_path, shape=(224, 224))
    top_score, top_class = model_transfer(image).topk(1, dim=1)
    breed = class_names[int(top_class.item())]
    # load the image and return the predicted breed
    return breed
In [65]:
predict_breed_transfer(dog_path_example)
Out[65]:
'Affenpinscher'

Step 5: Write your Algorithm

Write an algorithm that accepts a file path to an image and first determines whether the image contains a human, dog, or neither. Then,

  • if a dog is detected in the image, return the predicted breed.
  • if a human is detected in the image, return the resembling dog breed.
  • if neither is detected in the image, provide output that indicates an error.

You are welcome to write your own functions for detecting humans and dogs in images, but feel free to use the face_detector and dog_detector functions developed above. You are required to use your CNN from Step 4 to predict dog breed.

Some sample output for our algorithm is provided below, but feel free to design your own user experience!

Sample Human Output

(IMPLEMENTATION) Write your Algorithm

In [66]:
### TODO: Write your algorithm.
### Feel free to use as many code cells as needed.

def run_app(img_path):
    dog = dog_detector(img_path)
    human = face_detector(img_path)
    if not (human or dog):
        raise ValueError("Image contains neither a dog or a human, sorry")
    breed = predict_breed_transfer(img_path)
    if dog and human:
        print('UhOh! Looks like we met a werewolf?')
        print('This creature looks like a {}'.format(breed))
    elif dog:
        print('Oooh, look at this cute little {}'.format(breed))
    else:
        print("According to the Holly Great Computer, this human looks like a {}".format(breed))
    img = cv2.imread(img_path)
    plt.imshow(img)
    plt.show()
    return breed

Step 6: Test Your Algorithm

In this section, you will take your new algorithm for a spin! What kind of dog does the algorithm think that you look like? If you have a dog, does it predict your dog's breed accurately? If you have a cat, does it mistakenly think that your cat is a dog?

(IMPLEMENTATION) Test Your Algorithm on Sample Images!

Test your algorithm at least six images on your computer. Feel free to use any images you like. Use at least two human and two dog images.

In [67]:
## TODO: Execute your algorithm from Step 6 on
## at least 6 images on your computer.
## Feel free to use as many code cells as needed.

## suggested code, below
for file in np.hstack((human_files[:3], dog_files[:3])):
    run_app(file)
UhOh! Looks like we met a werewolf?
This creature looks like a Finnish spitz
According to the Holly Great Computer, this human looks like a Otterhound
According to the Holly Great Computer, this human looks like a Chinese shar-pei
Oooh, look at this cute little Australian shepherd
UhOh! Looks like we met a werewolf?
This creature looks like a Australian shepherd
Oooh, look at this cute little Australian shepherd

Now let's have fun

According to a well spread idea, dogs and masters often look alike. Let's see if our predictor agrees with that!

I've downloaded a few dog-master couples from this blog post and taken a picture of one of my relatives and his dog. Let's see if our algorithm classifies them accordingly!

In [68]:
from PIL import Image
# Set PIL to be tolerant of image files that are truncated.
from PIL import ImageFile
ImageFile.LOAD_TRUNCATED_IMAGES = True
from torchvision import transforms

def load_image_to_plot(img_path, shape):
    ''' 
       
    '''
    image = Image.open(img_path).convert('RGB')
    in_transform = transforms.Compose([
                            transforms.Resize(shape),
                            transforms.ToTensor(),
                            ])
    # discard the transparent, alpha channel (that's the :3) and add the batch dimension
    image = in_transform(image)[:3,:,:]
    return image
In [69]:
couples_pics = 'images/couples/couple_{}'

fig = plt.figure(figsize=(25, 12))
for couple_num in range(1,6):
    pic_path = couples_pics.format(couple_num)
    master_path = os.path.join(pic_path, 'master.png')
    dog_path= os.path.join(pic_path, 'dog.png')
    master = load_image_to_plot(master_path, imsize).numpy()
    dog = load_image_to_plot(dog_path, imsize).numpy()
    # master
    ax = fig.add_subplot(2, 5, couple_num + 5, xticks=[], yticks=[])
    plt.imshow(np.transpose(master, (1, 2, 0)))
    ax.set_title(predict_breed_transfer(master_path))
    # dog
    ax = fig.add_subplot(2, 5, couple_num, xticks=[], yticks=[])
    plt.imshow(np.transpose(dog, (1, 2, 0)))
    ax.set_title(predict_breed_transfer(dog_path))

It may be disapointing but, according to our classifier, these masters do not look like the same breed as their dogs. However, it doesn't mean that they do not look alike for us and, still, it was fun for me to play this little game!

Still, one could also notice that 3 out of the 4 dogs found online were correctly classified (number 1, 3 and 4).

Regarding my relative's dog, it was classified as as Affenpinscher, which it is not as it is a weird mix between a Yorkshire and a Poodle. However, Eben (our dog's name) actually could look like an Affenpinscher.

In [70]:
dog = load_image_to_plot(os.path.join(dog_dir, 'train/001.Affenpinscher/Affenpinscher_00001.jpg'), imsize).numpy()
plt.imshow(np.transpose(dog, (1, 2, 0)))
plt.title('An Affenpinscher')
Out[70]:
Text(0.5, 1.0, 'An Affenpinscher')

In order to go a little further in the game, let take a look at the scores for our couples.

In [71]:
for couple_num in range(1,6):
    print("Couple number {}".format(couple_num))
    pic_path = couples_pics.format(couple_num)
    master_path = os.path.join(pic_path, 'master.png')
    dog_path= os.path.join(pic_path, 'dog.png')
    # master
    master = load_image(master_path, shape=(224, 224))
    master_scores = F.softmax(model_transfer(master), dim=1)
    master_score, top_class = master_scores.topk(1, dim=1)
    master_breed = class_names[int(top_class.item())]
    # dog 
    dog = load_image(dog_path, shape=(224, 224))
    dog_scores = F.softmax(model_transfer(dog), dim=1)
    dog_score, top_class = dog_scores.topk(1, dim=1)
    dog_breed = class_names[int(top_class.item())]
    # cross_scores
    master_to_dog = master_scores[0, class_names.index(dog_breed)]
    dog_to_master = dog_scores[0, class_names.index(master_breed)]
    print("Classes: {}, {}".format(master_breed, dog_breed))
    print("Master scores : {}, {}".format(master_score.item(), master_to_dog))
    print("Dog scores: {}, {}".format(dog_to_master, dog_score.item()))
    print()
Couple number 1
Classes: Havanese, Irish setter
Master scores : 0.10888192802667618, 0.00048271429841406643
Dog scores: 4.318600481850519e-34, 0.99992835521698

Couple number 2
Classes: Chinese crested, Dandie dinmont terrier
Master scores : 0.011279340833425522, 0.009082811884582043
Dog scores: 0.0010046778479591012, 0.5820730328559875

Couple number 3
Classes: Chesapeake bay retriever, French bulldog
Master scores : 0.015326996333897114, 0.011426779441535473
Dog scores: 6.4585876412048875e-24, 0.9978029131889343

Couple number 4
Classes: Australian cattle dog, Bichon frise
Master scores : 0.010655884630978107, 0.007611989974975586
Dog scores: 1.9016009389360988e-07, 0.9629639387130737

Couple number 5
Classes: Dachshund, Affenpinscher
Master scores : 0.0160075556486845, 0.002960309386253357
Dog scores: 6.697010394418612e-05, 0.2974148094654083

In [88]:
# Look for actual breed of dog from couple number 2
for class_name in class_names:
    if 'schnoodle' in class_name:
        print(class_name)
        break
else:
    print("No Schnoodle in the classes used by our network")
No Schnoodle in the classes used by our network

Without surprise, our network is much more effective when it comes to attributing a breed to a dog than a human. In the second case, most of the scores could be those of a classifier which weights would be attributed randomly. This is not a surprise as the network was trained to classifies dog...not humans.

Also, one could notice that its decisions are also more distinct when classifying dogs that belongs to the actual output classes that dogs out of the breeds it is trained to classify. In the first case, the network provided the right answer with an associated probablity over 90%.

For uncathegorized dog, the classifier gives result with a much lower confidence (about 60% and 30% respectively). Taking a look on the net at pictures for the predicted dog breeds of dogs for couples number 2 and 5, one could see that the networks produces results that are fairly relevant, given the fact that it cannot provide the actual answer.

Question 6: Is the output better than you expected :) ? Or worse :( ? Provide at least three possible points of improvement for your algorithm.

Answer

Actually, the network is much better at recognizing dogs than I expected: its accuracy seems very decent for such a challenging task with a relatively small number of samples. I'm also quiet satisfied that the certainty of the provided answer is much higher for dogs present in the output classes than for other dogs.

The poor diagnosis provided for humans, which is close to random guess and differs for several pictures of the same person, is dispointing for our game. It is however not surprising as it requires the network to perform a task which is quiet far from its training goal.

Regarding the improvements that could be given to this model, I may have obtained similar results with a cheaper model than VGG19 which, would have resulted in lower costs to train and used the model. Training on GPUs would also have improved the cost of this step of the model creation!

In the present case, I stopped training the model after 20 epochs, which was already quiet expensive (my 8-procs computer worked during one night). The validation loss seemed to start stagnating however, I could maybe have scrounged a few points of accuracy by training it further.

Finally, my image augmentation procedure was fairly basic. I couls maybe have achieved better results by working on it. E.g. some authors use the center, and all the corners of their images whereas I just used a random crop.

Metamorphosis ?

As discussed above, the difference in scores between the dogs and masters are quiet dispointing in our previous game. Therefore, the main idea of this new game is to see what would happen if we modify the image of a master in order that it obtains a closer score to the one of its dog, while trying to maintain its "look".

In order to do so, a procedure similar to the one used in the style transfer exercise is attempted : the input (master) image is optimized in order to minimize a loss function which describes a compromise between "looking like the master" and "beeing categorized like the dog".

In order to try to ensure that the image keeps looking like the master along the optimization, a "content loss" is defined exactly as in the style transfer exercise from the features identified in this paper as key for sementical content preservation.

A second term is added to the loss in order to try to make the score predicted by the model as close as possible as the one of the dog.

In [73]:
model_transfer = models.vgg19(pretrained=True)
model_transfer.classifier[6] = nn.Linear(4096, n_class)
model_transfer.load_state_dict(torch.load(os.path.join(train_dir, save_name)))
# Freeze training for all "features" layers
for param in model_transfer.features.parameters():
    param.requires_grad = False
model_transfer.eval()
print('Model loaded')
Model loaded
In [74]:
def get_features(image, model, layers=None):
    """ Run an image forward through a model and get the features for 
        a set of layers. Default layers are for VGGNet matching Gatys et al (2016)
    """
    if layers is None:
        layers = {
                  #'0': 'conv1_1',
                  #'5': 'conv2_1', 
                  #'10': 'conv3_1', 
                  #'19': 'conv4_1',
                  21: 'conv4_2',  ## content representation
                  #'28': 'conv5_1'
        }
        
    features = {}
    x = image
    # model._modules is a dictionary holding each module in the model
    for lay_num in range(0,37):
        layer = model.features[lay_num]
        x = layer(x)
        if lay_num in layers:
            features[layers[lay_num]] = x
    return features
In [75]:
# load in content and style image
content = load_image('images/couples/couple_1/master.png', shape=(imsize, imsize))
target_image = load_image('images/couples/couple_1/dog.png', shape=(imsize, imsize))
In [76]:
# get content and style features only once before training
content_features = get_features(content, model_transfer)
In [77]:
# get output of model for target
target_score = model_transfer(target_image).clone().detach().to(device)
top_score, top_class = target_score.topk(1, dim=1)

# create a third "target" image and prep it for change
# it is a good idea to start off with the target as a copy of our *content* image
# then iteratively change its style
target = content.clone().requires_grad_(True).to(device)

Let's get an idea of the order of magnitude of the features squared values (to get an idea of the associated loss values to be expected):

In [78]:
torch.mean(content_features['conv4_2'])**2
Out[78]:
tensor(1.1817)
In [79]:
def im_convert(tensor):
    """ Display a tensor as an image. """
    image = tensor.to("cpu").clone().detach()
    image = image.numpy().squeeze()
    image = image.transpose(1,2,0)
    image = image * np.array((0.229, 0.224, 0.225)) + np.array((0.485, 0.456, 0.406))
    image = image.clip(0, 1)
    return image

To begin with, the score weight is set to a very high value so that most of effort is on fitting the score with a very high freedom on the content (which actually, is of no use as will be seen later).

# for displaying the target image, intermittently
show_every = 500

# weights
content_weight = 1.
score_weight = 1e6

# iteration hyperparameters
optimizer = optim.Adam([target], lr=0.003)
style_criterion = torch.nn.MSELoss()
steps = 5000 # decide how many iterations to update your image (5000)

for ii in range(1, steps+1):
    # get the features from your target image
    target_features = get_features(target, model_transfer)
    prediction = model_transfer(target)
    # the content loss <> is the content far from initial image?
    content_loss = torch.mean((target_features['conv4_2'] - content_features['conv4_2'])**2)
    # the score loss <> is it the right label?
    score_loss = style_criterion(prediction, target_score)
    # calculate the *total* loss
    total_loss = content_weight * content_loss + score_weight * score_loss
    # update your target image
    optimizer.zero_grad()
    total_loss.backward()
    optimizer.step()
    print(ii, total_loss.item(), score_loss.item(), content_loss.item())
    # display intermediate images and print the loss
    if  ii % show_every == 0:
        print('Total loss: ', total_loss.item())
        torch.save(target, 'dogged_face.pt')
        plt.imshow(im_convert(target))
        plt.show()

torch.save(target, 'dogged_face.pt')
# Output when computation stopped
# it. number, total loss, score loss, content loss
.
.
.
2356 251266.09375 0.2512569725513458 9.125899314880371
2357 251237.515625 0.251228392124176 9.126667022705078
In [81]:
result = torch.load('dogged_face.pt')

The computations were stopped after some time as the error had been stagnating for the last thousand iterations (over approximately 3000 with the restarts).

The cells located here-under traduce the fact that, as can be ssen from the low MSE ($\approx 0.25$), the score of the dog image is pretty well approximated with the resulting modified master image!

In [82]:
F.softmax(model_transfer(result), dim=1).topk(1,dim=1)
Out[82]:
torch.return_types.topk(
values=tensor([[1.0000]], grad_fn=<TopkBackward>),
indices=tensor([[85]]))
In [83]:
F.softmax(model_transfer(target_image), dim=1).topk(1,dim=1)
Out[83]:
torch.return_types.topk(
values=tensor([[0.9999]], grad_fn=<TopkBackward>),
indices=tensor([[85]]))
In [84]:
(model_transfer(result) - model_transfer(target_image)).max()
Out[84]:
tensor(1.8587, grad_fn=<MaxBackward1>)
In [85]:
model_transfer(target_image).max()
Out[85]:
tensor(17.1741, grad_fn=<MaxBackward1>)

However, as can be seen when plotting the resulting image, There seem to be almost no modification in the original master image!

In [86]:
plt.imshow(im_convert(result))
plt.show()

This can be confirmed by plotting the difference between both initial and obtained images:

In [87]:
plt.imshow(im_convert(content - result))
plt.show()

In conclusion, even if I admit that obtaining an hybridated image of a human containing dog-like features would have been cool (as the tree/building deep-dream example from the class), this result also has its interest: in my opinion, it is a very good example of the limitations of the network architectures I have used so far. It points out the fact that even if our networks may have decent scores in validation and testing, fooling them still remains an easy job. (which reminds me of various newe about researchers fooling facial recognition A.I.)

I therfore wonder: is there a way to build a more robust classifier? Is there a way to demonstrate the robustness of a classifier?

Let's find out in the next chapters! (And on the net actually)